<template>
  <div class="ai-chat-container">
    <div class="chat-header">
               <div class="message-avatar ai-thinking-avatar">
            <svg viewBox="0 0 100 100" width="40" height="40" xmlns="http://www.w3.org/2000/svg">
              <!-- 机器人头部 - 思考中的样式 -->
              <defs>
                <linearGradient id="robot-thinking" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" stop-color="#4facfe">
                    <animate attributeName="stop-color" values="#4facfe;#00f2fe;#4facfe" dur="3s" repeatCount="indefinite" />
                  </stop>
                  <stop offset="100%" stop-color="#00f2fe">
                    <animate attributeName="stop-color" values="#00f2fe;#4facfe;#00f2fe" dur="3s" repeatCount="indefinite" />
                  </stop>
                </linearGradient>
              </defs>
              
              <!-- 主体 -->
              <rect x="30" y="20" width="40" height="60" rx="10" ry="10" fill="url(#robot-thinking)" />
              
              <!-- 天线 -->
              <line x1="40" y1="20" x2="40" y2="10" stroke="#4facfe" stroke-width="2" />
              <circle cx="40" cy="10" r="3" fill="#00f2fe" />
              <line x1="60" y1="20" x2="60" y2="10" stroke="#4facfe" stroke-width="2" />
              <circle cx="60" cy="10" r="3" fill="#00f2fe" />
              
              <!-- 眼睛 - 思考状态 -->
              <circle cx="40" cy="40" r="7" fill="#ffffff" />
              <circle cx="60" cy="40" r="7" fill="#ffffff" />
              
              <!-- 眼睛动画 - 转动的思考 -->
              <circle cx="40" cy="40" r="3.5" fill="#0f172a">
                <animateTransform attributeName="transform" type="rotate" from="0 40 40" to="360 40 40" dur="3s" repeatCount="indefinite" />
              </circle>
              <circle cx="60" cy="40" r="3.5" fill="#0f172a">
                <animateTransform attributeName="transform" type="rotate" from="0 60 40" to="360 60 40" dur="3s" repeatCount="indefinite" />
              </circle>
              
              <!-- 嘴巴 - 思考状态 -->
              <rect x="40" y="55" width="20" height="5" rx="2.5" ry="2.5" fill="#ffffff">
                <animate attributeName="width" values="20;15;20" dur="1.5s" repeatCount="indefinite" />
                <animate attributeName="x" values="40;42.5;40" dur="1.5s" repeatCount="indefinite" />
              </rect>
              
              <!-- 耳朵/侧部装饰 -->
              <rect x="25" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-thinking)" />
              <rect x="70" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-thinking)" />
              
              <!-- 思考泡泡 -->
              <circle cx="70" cy="25" r="3" fill="#ffffff" opacity="0.8">
                <animate attributeName="cy" values="25;20;25" dur="2s" repeatCount="indefinite" />
              </circle>
              <circle cx="78" cy="20" r="2" fill="#ffffff" opacity="0.6">
                <animate attributeName="cy" values="20;15;20" dur="2.5s" repeatCount="indefinite" />
              </circle>
            </svg>
          </div><h2 class="chat-title">AI金融助手</h2>
      <div class="chat-subtitle">利用人工智能解答您的金融问题</div>
    </div>

    <div class="chat-content">
      <div class="chat-history" ref="chatHistoryRef">
        <template v-if="chatHistory.length === 0">
          <div class="welcome-message">          <div class="welcome-icon">            <svg viewBox="0 0 100 100" width="80" height="80" xmlns="http://www.w3.org/2000/svg">
              <!-- 机器人头部 - 使用渐变色 -->
              <defs>
                <linearGradient id="robot-head" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" stop-color="#4facfe" />
                  <stop offset="100%" stop-color="#00f2fe" />
                </linearGradient>
                <radialGradient id="eye-shine" cx="35%" cy="35%" r="60%" fx="35%" fy="35%">
                  <stop offset="0%" stop-color="#ffffff" stop-opacity="0.9" />
                  <stop offset="100%" stop-color="#f0f0f0" stop-opacity="0.1" />
                </radialGradient>
              </defs>
              
              <!-- 主体 -->
              <rect x="30" y="20" width="40" height="60" rx="10" ry="10" fill="url(#robot-head)" />
              
              <!-- 天线 -->
              <line x1="40" y1="20" x2="40" y2="10" stroke="#4facfe" stroke-width="2" />
              <circle cx="40" cy="10" r="3" fill="#00f2fe" />
              <line x1="60" y1="20" x2="60" y2="10" stroke="#4facfe" stroke-width="2" />
              <circle cx="60" cy="10" r="3" fill="#00f2fe" />
              
              <!-- 眼睛外圈 -->
              <circle cx="40" cy="40" r="7" fill="#ffffff" />
              <circle cx="60" cy="40" r="7" fill="#ffffff" />
              
              <!-- 眼睛内部 -->
              <circle cx="40" cy="40" r="3.5" fill="#0f172a" />
              <circle cx="60" cy="40" r="3.5" fill="#0f172a" />
              
              <!-- 眼睛高光 -->
              <circle cx="38.5" cy="38.5" r="1.5" fill="white" />
              <circle cx="58.5" cy="38.5" r="1.5" fill="white" />
              
              <!-- 嘴巴 -->
              <rect x="40" y="55" width="20" height="5" rx="2.5" ry="2.5" fill="#ffffff" />
              
              <!-- 耳朵/侧部装饰 -->
              <rect x="25" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-head)" />
              <rect x="70" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-head)" />
              
              <!-- 胸部指示灯 -->
              <circle cx="50" cy="70" r="3" fill="#ffffff">
                <animate attributeName="opacity" values="0.5;1;0.5" dur="2s" repeatCount="indefinite" />
              </circle>
            </svg>
          </div>
            <h3>您好！我是您的AI金融助手</h3>
            <p>我可以回答有关金融知识、投资策略、市场分析等问题。</p>
            <div class="suggestion-container">
              <h4>您可以尝试这些问题：</h4>
              <div class="suggestion-list">
                <div class="suggestion-item" v-for="(suggestion, index) in suggestions" :key="index" @click="askSuggestion(suggestion)">
                  {{ suggestion }}
                </div>
              </div>
            </div>
          </div>
        </template>
        
        <template v-else>          <div v-for="(msg, index) in chatHistory" :key="index" :class="['message', 
            msg.role === 'user' ? 'user-message' : 
            msg.role === 'system' ? 'system-message' : 'assistant-message']">
            <div class="message-avatar">
              <span v-if="msg.role === 'user'">👤</span>
              <span v-else-if="msg.role === 'system'">ℹ️</span>
              <span v-else>
                <svg viewBox="0 0 100 100" width="30" height="30" xmlns="http://www.w3.org/2000/svg">
                  <!-- 机器人头部 -->
                  <defs>
                    <linearGradient id="robot-chat" x1="0%" y1="0%" x2="100%" y2="100%">
                      <stop offset="0%" stop-color="#4facfe" />
                      <stop offset="100%" stop-color="#00f2fe" />
                    </linearGradient>
                  </defs>
                  
                  <!-- 主体 -->
                  <rect x="30" y="20" width="40" height="60" rx="10" ry="10" fill="url(#robot-chat)" />
                  
                  <!-- 天线 -->
                  <line x1="40" y1="20" x2="40" y2="10" stroke="#4facfe" stroke-width="2" />
                  <circle cx="40" cy="10" r="3" fill="#00f2fe" />
                  <line x1="60" y1="20" x2="60" y2="10" stroke="#4facfe" stroke-width="2" />
                  <circle cx="60" cy="10" r="3" fill="#00f2fe" />
                  
                  <!-- 眼睛 -->
                  <circle cx="40" cy="40" r="7" fill="#ffffff" />
                  <circle cx="60" cy="40" r="7" fill="#ffffff" />
                  <circle cx="40" cy="40" r="3.5" fill="#0f172a" />
                  <circle cx="60" cy="40" r="3.5" fill="#0f172a" />
                  <circle cx="38.5" cy="38.5" r="1.5" fill="white" />
                  <circle cx="58.5" cy="38.5" r="1.5" fill="white" />
                  
                  <!-- 嘴巴 -->
                  <rect x="40" y="55" width="20" height="5" rx="2.5" ry="2.5" fill="#ffffff" />
                  
                  <!-- 耳朵/侧部装饰 -->
                  <rect x="25" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-chat)" />
                  <rect x="70" y="35" width="5" height="15" rx="2.5" ry="2.5" fill="url(#robot-chat)" />
                </svg>
              </span>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(msg.content)"></div>
              <div class="message-time" v-if="msg.time">{{ msg.time }}</div>
            </div>
          </div>
        </template>        <!-- 加载状态 - 思考中显示 -->
        <div v-if="isLoading" class="message assistant-message thinking-message">
          <div class="message-avatar ai-thinking-avatar">�</div>
          <div class="message-content thinking-content">
            <div class="thinking-header">
              <div class="thinking-icon">
                <svg viewBox="0 0 24 24" width="28" height="28" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
                  <circle cx="12" cy="12" r="10"></circle>
                  <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>
                  <line x1="12" y1="17" x2="12.01" y2="17"></line>
                </svg>
              </div>
              <div class="thinking-title">AI深度思考中...</div>
            </div>
              <div class="thinking-process">
              <div class="thinking-step" :class="{ active: activeThinkingStep === 0 }">
                <div class="step-icon">📊</div>
                <div class="step-text">分析您的问题</div>
              </div>
              <div class="thinking-step" :class="{ active: activeThinkingStep === 1 }">
                <div class="step-icon">🔍</div>
                <div class="step-text">检索相关知识</div>
              </div>
              <div class="thinking-step" :class="{ active: activeThinkingStep === 2 }">
                <div class="step-icon">💡</div>
                <div class="step-text">生成专业解答</div>
              </div>
            </div>
            
            <div class="thinking-description">
              正在处理您的金融问题，将为您提供专业、全面的解答
            </div>
            
            <div class="thinking-animation">
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
              <div class="thinking-dot"></div>
            </div>
            
            <div class="thinking-tip">
              <div class="tip-icon">💼</div>
              <div class="tip-text">专业提示：AI分析问题需要一定时间，复杂金融问题可能需要更长时间思考</div>
            </div>
          </div>
        </div>
      </div>      <div class="chat-input-container">
        <div class="input-wrapper">
          <el-input
            v-model="userQuestion"
            type="textarea"
            :rows="3.5"
            placeholder="请输入您的金融问题..."
            resize="none"
            @keydown.enter.prevent="sendQuestion"
            :disabled="isLoading || !isUserLoggedIn"
          />
          <div class="function-buttons">
            <el-tooltip content="上传附件" placement="top">
              <el-button 
                class="function-button" 
                circle 
                size="small"
                :disabled="isLoading || !isUserLoggedIn"
                @click="handleFileUpload"
              >
                <el-icon><Upload /></el-icon>
              </el-button>
            </el-tooltip>            <el-tooltip content="历史记录" placement="top">
              <el-button 
                class="function-button" 
                circle 
                size="small"
                :disabled="isLoading || !isUserLoggedIn"
                @click="toggleHistoryPanel"
              >
                <el-icon><Clock /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
        <el-button 
          type="primary" 
          class="send-button" 
          @click="sendQuestion" 
          :loading="isLoading"
          :disabled="!userQuestion.trim() || !isUserLoggedIn"
        >
          发送
        </el-button>
      </div>
      
      <!-- 文件上传对话框 -->
      <el-dialog
        v-model="showFileDialog"
        title="上传附件"
        width="30%"
      >
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          :file-list="fileList"
        >
          <el-button type="primary">选择文件</el-button>          <template #tip>
            <div class="el-upload__tip">支持PDF、Word、Excel、PowerPoint、图片以及多种文本文件格式</div>
          </template>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showFileDialog = false">取消</el-button>
            <el-button type="primary" @click="uploadFile" :loading="uploading">
              上传并分析
            </el-button>
          </span>
        </template>
      </el-dialog>
      
      <div v-if="!isUserLoggedIn" class="login-notice">
        <el-alert
          title="请先登录"
          type="info"
          description="登录后即可使用AI问答功能"
          show-icon
          :closable="false"
        >
          <template #default>
            <el-button type="primary" size="small" @click="goToLogin" style="margin-top: 8px;">
              去登录
            </el-button>
          </template>
        </el-alert>
      </div>
    </div>
    
    <div class="history-panel" :class="{ 'history-panel-open': isHistoryOpen }">
      <div class="history-panel-header">
        <h3>历史对话</h3>
        <el-button type="text" @click="toggleHistoryPanel">{{ isHistoryOpen ? '关闭' : '打开' }}</el-button>
      </div>
      
      <div v-if="isHistoryOpen" class="history-list">
        <div v-if="loadingHistory" class="history-loading">加载历史记录中...</div>
        <div v-else-if="savedHistory.length === 0" class="no-history">暂无历史记录</div>
        <div v-else class="history-items">
          <div 
            v-for="(record, index) in savedHistory" 
            :key="record.id" 
            class="history-item" 
            @click="loadHistoryItem(record)"
          >
            <div class="history-question">{{ truncateText(record.question, 30) }}</div>
            <div class="history-time">{{ record.created_at }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { Upload, Clock, Search } from '@element-plus/icons-vue';

const router = useRouter();
const chatHistoryRef = ref(null);
const userQuestion = ref('');
const chatHistory = ref([]);
const isLoading = ref(false);
const isHistoryOpen = ref(false);
const savedHistory = ref([]);
const loadingHistory = ref(false);
const user = ref(null);
const isUserLoggedIn = computed(() => user.value !== null);
const activeThinkingStep = ref(0); // 当前活跃的思考步骤
const thinkingStepInterval = ref(null); // 思考步骤的定时器

// 新增功能相关变量
const showFileDialog = ref(false); // 文件上传对话框
const fileList = ref([]); // 上传文件列表
const uploading = ref(false); // 上传状态

// 建议问题列表
const suggestions = [
  "什么是ETF？它有什么优势？",
  "如何理解市盈率(PE)和市净率(PB)？",
  "债券投资有哪些风险？",
  "如何评估一个公司的财务健康状况？",
  "什么是资产配置？为什么它很重要？"
];

onMounted(() => {
  // 从localStorage读取用户信息
  const userStr = localStorage.getItem('user');
  if (userStr) {
    user.value = JSON.parse(userStr);
    // 如果用户已登录，加载历史记录
    if (user.value) {
      fetchChatHistory();
    }
  }
  
  // 监听窗口大小变化，适应移动设备
  window.addEventListener('resize', adjustHistoryPanel);
  adjustHistoryPanel();
});

// 在组件销毁前清除定时器
onBeforeUnmount(() => {
  if (thinkingStepInterval.value) {
    clearInterval(thinkingStepInterval.value);
  }
  // 移除窗口大小变化监听
  window.removeEventListener('resize', adjustHistoryPanel);
});

// 根据窗口大小调整历史面板
function adjustHistoryPanel() {
  if (window.innerWidth < 768) {
    isHistoryOpen.value = false;
  }
}

// 切换历史记录面板
function toggleHistoryPanel() {
  isHistoryOpen.value = !isHistoryOpen.value;
  
  // 如果打开面板且还没加载历史记录，则加载
  if (isHistoryOpen.value && savedHistory.value.length === 0 && isUserLoggedIn.value) {
    fetchChatHistory();
  }
}

// 获取聊天历史记录
async function fetchChatHistory() {
  if (!user.value || !user.value.id) return;
  
  loadingHistory.value = true;
  try {
    const response = await axios.get(`http://localhost:5000/api/chat/history?user_id=${user.value.id}`);
    if (response.data.code === 0) {
      savedHistory.value = response.data.data;
    } else {
      console.error('获取历史记录失败:', response.data.msg);
    }
  } catch (error) {
    console.error('获取历史记录错误:', error);
  } finally {
    loadingHistory.value = false;
  }
}

// 加载历史记录项目
function loadHistoryItem(record) {
  // 清空当前对话
  chatHistory.value = [];
  
  // 添加历史问答到当前对话
  chatHistory.value.push(
    { role: 'user', content: record.question, time: formatTime(new Date(record.created_at)) },
    { role: 'assistant', content: record.answer, time: formatTime(new Date(record.created_at)) }
  );
  
  // 滚动到底部
  scrollToBottom();
}

// 发送问题
async function sendQuestion() {
  if (!userQuestion.value.trim() || isLoading.value || !isUserLoggedIn.value) return;
  
  // 添加用户问题到聊天历史
  const question = userQuestion.value.trim();
  chatHistory.value.push({
    role: 'user',
    content: question,
    time: formatTime(new Date())
  });
  
  userQuestion.value = ''; // 清空输入框
  isLoading.value = true;
  
  // 滚动到底部
  await scrollToBottom();
  
  // 启动思考步骤动画
  startThinkingStepAnimation();
  
  // 准备历史对话记录（最近5轮）
  const recentMessages = [];  for (let i = Math.max(0, chatHistory.value.length - 10); i < chatHistory.value.length - 1; i++) {
    if (chatHistory.value[i]) {
      recentMessages.push({
        role: chatHistory.value[i].role,
        content: chatHistory.value[i].content
      });
    }
  }    try {
      // 调用API获取回答
    const response = await axios.post('http://localhost:5000/api/chat', {
      user_id: user.value.id,
      question: question,
      history: recentMessages
    });
    
    if (response.data.code === 0) {
      // 添加AI回答
      chatHistory.value.push({
        role: 'assistant',
        content: response.data.data.answer,
        time: formatTime(new Date())
      });
      
      // 更新历史记录
      fetchChatHistory();
    } else {
      // 显示错误信息
      let errorMsg = response.data.msg;
      
      // 检测特定错误类型
      if (errorMsg.includes('401') && errorMsg.includes('令牌')) {
        errorMsg = "API密钥已过期或无效。请联系管理员更新智谱AI API密钥，或参考后端目录中的API_KEY_FIX.md文件获取帮助。";
      }
      
      chatHistory.value.push({
        role: 'assistant',
        content: `抱歉，出现了问题：${errorMsg}`,
        time: formatTime(new Date())
      });
    }
  } catch (error) {
    console.error('聊天请求错误:', error);
    
    // 提供更友好的错误信息
    let errorMsg = error.message;
    
    // 检查是否为连接错误
    if (error.message.includes('Network Error') || error.code === 'ECONNREFUSED') {
      errorMsg = "无法连接到后端服务。请确保后端服务器正在运行，并且地址配置正确。";
    }
    
    chatHistory.value.push({
      role: 'assistant',
      content: `抱歉，服务暂时不可用：${errorMsg}`,
      time: formatTime(new Date())
    });
  } finally {
    // 停止思考步骤动画
    stopThinkingStepAnimation();
    isLoading.value = false;
    await scrollToBottom();
  }
}

// 启动思考步骤动画
function startThinkingStepAnimation() {
  // 重置到第一步
  activeThinkingStep.value = 0;
  
  // 清除之前的定时器（如果存在）
  if (thinkingStepInterval.value) {
    clearInterval(thinkingStepInterval.value);
  }
  
  // 设置步骤切换的定时器，每2秒切换到下一步
  thinkingStepInterval.value = setInterval(() => {
    activeThinkingStep.value = (activeThinkingStep.value + 1) % 3;
  }, 2000);
}

// 停止思考步骤动画
function stopThinkingStepAnimation() {
  if (thinkingStepInterval.value) {
    clearInterval(thinkingStepInterval.value);
    thinkingStepInterval.value = null;
  }
}

// 提问建议问题
function askSuggestion(suggestion) {
  userQuestion.value = suggestion;
  sendQuestion();
}

// 跳转到登录页
function goToLogin() {
  router.push('/login');
}

// 格式化消息内容，简单处理换行和空格
function formatMessage(content) {
  // 简单替换换行为<br>标签，空格为&nbsp;
  return content
    .replace(/\n/g, '<br>')
    .replace(/  /g, '&nbsp;&nbsp;');
}

// 格式化时间
function formatTime(date) {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    hour12: false 
  });
}

// 截断文本
function truncateText(text, maxLength) {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
}

// 滚动到底部
async function scrollToBottom() {
  await nextTick();
  if (chatHistoryRef.value) {
    chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight;
  }
}

// 监听聊天历史变化，自动滚动到底部
watch(chatHistory, () => {
  scrollToBottom();
});

// 处理文件上传对话框
function handleFileUpload() {
  if (!isUserLoggedIn.value) return;
  showFileDialog.value = true;
  fileList.value = [];
}

// 处理文件变化
function handleFileChange(file) {
  fileList.value = [file];
}

// 上传并分析文件
async function uploadFile() {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件');
    return;
  }
  // 检查文件类型和大小
  const file = fileList.value[0];
  const allowedTypes = [
    'application/pdf', 
    'text/csv',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'text/plain',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'image/png',
    'image/jpeg',
    'image/jpg',
    'image/gif',
    'image/bmp',
    'text/markdown',
    'text/x-python'
  ];
  
  // 获取文件扩展名
  const fileName = file.name.toLowerCase();
  const fileExtension = fileName.split('.').pop();
  const allowedExtensions = ['pdf', 'csv', 'xls', 'xlsx', 'txt', 'doc', 'docx', 'ppt', 'pptx', 
                            'png', 'jpg', 'jpeg', 'gif', 'bmp', 'md', 'py'];
  
  // 检查文件类型（通过MIME类型或扩展名）
  if (!allowedTypes.includes(file.raw.type) && !allowedExtensions.includes(fileExtension)) {
    ElMessage.error('不支持的文件格式，请上传常见的文档、表格、图片或文本文件');
    return;
  }
  
  // 检查文件大小（限制为50MB，图片限制为5MB）
  const isImage = ['png', 'jpg', 'jpeg', 'gif', 'bmp'].includes(fileExtension);
  const maxSize = isImage ? 5 * 1024 * 1024 : 50 * 1024 * 1024; // 图片5MB，其他50MB
  
  if (file.raw.size > maxSize) {
    ElMessage.error(isImage ? '图片过大，请上传5MB以下的图片' : '文件过大，请上传50MB以下的文件');
    return;
  }

  uploading.value = true;
  try {
    // 显示上传中提示
    ElMessage.info('文件上传中，请稍候...');
    
    // 创建FormData对象
    const formData = new FormData();
    formData.append('file', fileList.value[0].raw);
    formData.append('user_id', user.value.id);
    
    // 调用后端上传接口
    const response = await axios.post('http://localhost:5000/api/chat/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 60000 // 增加超时时间到60秒
    });
    
    if (response.data.code === 0) {
      showFileDialog.value = false;
      ElMessage.success('文件上传成功，正在分析...');
      
      // 添加文件分析信息到聊天历史
      chatHistory.value.push({
        role: 'system',
        content: `正在分析文件：${fileList.value[0].name}`,
        time: formatTime(new Date())
      });
      
      await scrollToBottom();
      
      // 添加分析结果到聊天历史
      const result = response.data.data?.analysis || '文件已上传，但分析结果为空';
      chatHistory.value.push({
        role: 'assistant',
        content: result,
        time: formatTime(new Date())
      });
      
      await scrollToBottom();    } else {
      ElMessage.error(response.data.msg || '文件上传失败');
      
      // 在聊天窗口中显示错误信息
      chatHistory.value.push({
        role: 'system',
        content: `文件处理失败：${response.data.msg || '未知错误'}`,
        time: formatTime(new Date())
      });
      
      await scrollToBottom();
      showFileDialog.value = false;
    }
  } catch (error) {
    console.error('文件上传错误:', error);
    
    // 更详细的错误处理
    let errorMsg = '文件上传服务异常，请稍后重试';
    
    if (error.response) {
      // 服务器返回了错误响应
      errorMsg = error.response.data?.msg || `服务器错误: ${error.response.status}`;
    } else if (error.request) {
      // 请求发出但没有收到响应
      errorMsg = '无法连接到服务器，请检查网络连接';
    } else if (error.message && error.message.includes('timeout')) {
      // 请求超时
      errorMsg = '文件处理超时，请尝试上传较小的文件';
    }
    
    ElMessage.error(errorMsg);
    
    // 在聊天窗口中显示错误信息
    chatHistory.value.push({
      role: 'system',
      content: `文件上传失败：${errorMsg}`,
      time: formatTime(new Date())
    });
    
    await scrollToBottom();
    showFileDialog.value = false;
  } finally {
    uploading.value = false;
  }
}


</script>

<style scoped>
.ai-chat-container {
  display: grid;
  grid-template-columns: 100px 1fr;
  height: 100%;
  position: relative;
  overflow: hidden;
  background-color: #f9fafb;
}

.chat-header {
  position: relative;
  width: 100%; /* 控制蓝色背景区域的宽度，原来是100%，现在缩小到65% */
  padding: 1.5rem;
  background: linear-gradient(to right, #4facfe, #00f2fe);
  color: white;
  border-bottom: 1px solid #e2e8f0;
  box-sizing: border-box;
  margin-right: auto;
  border-bottom-right-radius: 2rem; /* 右下角添加圆角，使过渡更自然 */
}

.chat-title {
  margin: 3;
  font-size: 1.5rem;
  font-weight: 600;
}

.chat-subtitle {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  opacity: 0.8;
}

.chat-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  padding: 0;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  scroll-behavior: smooth;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 2.5rem 2rem;
  background: linear-gradient(to bottom right, white, #f0f9ff);
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(59, 130, 246, 0.1);
  margin: 2rem auto;
  max-width: 90%;
  position: relative;
  overflow: hidden;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.welcome-message::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(to right, #4facfe, #00f2fe);
}

.welcome-icon {  font-size: 4rem;
  margin-bottom: 1.5rem;
  background: linear-gradient(to right, #4facfe, #00f2fe);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0px); }
}

.suggestion-container {
  margin-top: 1.5rem;
  width: 100%;
}

.suggestion-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  justify-content: center;
  margin-top: 0.75rem;
}

.suggestion-item {
  background-color: #eef2ff;
  color: #4f46e5;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.suggestion-item:hover {
  background-color: #e0e7ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message {
  display: flex;
  margin-bottom: 1.5rem;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  margin-right: 0.75rem;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-message .message-avatar {
  background-color: #4f46e5;
  color: white;
}

.assistant-message .message-avatar {
  background-color: #0ea5e9;
  color: white;
}

/* 系统消息样式 */
.system-message .message-content {
  background-color: #f1f5f9;
  color: #475569;
  border-left: 3px solid #94a3b8;
  font-style: italic;
}

.system-message .message-avatar {
  background-color: #94a3b8;
  color: white;
}

.message-content {
  flex: 1;
  padding: 1rem 1.25rem;
  border-radius: 0.75rem;
  overflow-wrap: break-word;
  word-break: break-word;
  max-width: calc(100% - 60px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.user-message .message-content {
  background-color: #eff6ff;
  color: #1e3a8a;
  border-top-left-radius: 0;
}

.assistant-message .message-content {
  background-color: white;
  color: #0f172a;
  border-top-right-radius: 0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
}

.message-content:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.message-text {
  line-height: 1.6;
  white-space: pre-wrap;
}

.message-text :deep(br) {
  display: block;
  content: "";
  margin-top: 0.5rem;
}

.message-time {
  font-size: 0.75rem;
  color: #64748b;
  margin-top: 0.5rem;
  text-align: right;
}

.thinking-message {
  z-index: 10;
}

.thinking-content {
  background: linear-gradient(135deg, #ebf8ff, #e6f7ff, #f0f9ff) !important;
  border: 1px solid rgba(14, 165, 233, 0.3);
  padding: 1.5rem !important;
  border-radius: 1rem !important;
  box-shadow: 0 10px 25px rgba(14, 165, 233, 0.15) !important;
}

.ai-thinking-avatar {
  background: linear-gradient(135deg, #0ea5e9, #3b82f6) !important;
  width: 42px !important;
  height: 42px !important;
  font-size: 1.5rem !important;
  animation: pulseAvatar 2s infinite;
  box-shadow: 0 0 15px rgba(14, 165, 233, 0.5) !important;
}

@keyframes pulseAvatar {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); box-shadow: 0 0 20px rgba(14, 165, 233, 0.7) !important; }
  100% { transform: scale(1); }
}

.thinking-header {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
  border-bottom: 1px solid rgba(14, 165, 233, 0.2);
  padding-bottom: 0.75rem;
}

.thinking-icon {
  margin-right: 0.75rem;
  color: #0ea5e9;
  animation: pulse 2s infinite;
}

.thinking-title {
  font-weight: 600;
  font-size: 1.25rem;
  color: #0369a1;
  background: linear-gradient(to right, #0ea5e9, #2563eb);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.thinking-process {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1.25rem;
  padding: 0.75rem;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 0.75rem;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.thinking-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  opacity: 0.6;
  transition: all 0.3s ease;
  position: relative;
  padding: 0 0.5rem;
}

.thinking-step.active {
  opacity: 1;
}

.thinking-step.active .step-icon {
  transform: scale(1.1);
  box-shadow: 0 5px 15px rgba(14, 165, 233, 0.3);
}

.thinking-step::after {
  content: '';
  position: absolute;
  top: 15px;
  right: -50%;
  width: 50%;
  height: 2px;
  background: #e2e8f0;
  z-index: 0;
}

.thinking-step:last-child::after {
  display: none;
}

.step-icon {
  font-size: 1.25rem;
  background: white;
  width: 36px;
  height: 36px;
  border-radius: 10%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0.5rem;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  z-index: 1;
  transition: all 0.3s ease;
}

.step-text {
  font-size: 0.75rem;
  color: #0c4a6e;
  text-align: center;
  font-weight: 500;
}

.thinking-description {
  color: #0c4a6e;
  margin-bottom: 1.25rem;
  font-size: 0.875rem;
  text-align: center;
  font-weight: 500;
  line-height: 1.5;
}

.thinking-animation {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  justify-content: center;
  height: 1.5rem;
  margin-bottom: 1.25rem;
  padding: 0.5rem;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 1rem;
}

.thinking-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: linear-gradient(to bottom, #0ea5e9, #0284c7);
  opacity: 0.8;
  animation: wave 1.5s infinite ease-in-out;
}

.thinking-dot:nth-child(1) { animation-delay: 0s; }
.thinking-dot:nth-child(2) { animation-delay: 0.2s; }
.thinking-dot:nth-child(3) { animation-delay: 0.4s; }
.thinking-dot:nth-child(4) { animation-delay: 0.6s; }
.thinking-dot:nth-child(5) { animation-delay: 0.8s; }
.thinking-dot:nth-child(6) { animation-delay: 1.0s; }
.thinking-dot:nth-child(7) { animation-delay: 1.2s; }

.thinking-tip {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 0.75rem;
  border-radius: 0.75rem;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  border-left: 3px solid #0ea5e9;
}

.tip-icon {
  font-size: 1.25rem;
  margin-right: 0.75rem;
  animation: bounce 2s infinite;
}

.tip-text {
  font-size: 0.8rem;
  color: #0369a1;
  line-height: 1.5;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

@keyframes wave {
  0%, 40%, 100% { transform: translateY(0); }
  20% { transform: translateY(-10px); box-shadow: 0 10px 15px -3px rgba(14, 165, 233, 0.3); }
}

@keyframes pulse {
  0% { transform: scale(0.95); opacity: 0.7; }
  50% { transform: scale(1.05); opacity: 1; }
  100% { transform: scale(0.95); opacity: 0.7; }
}

.chat-input-container {
  padding: 1rem 1.5rem;
  background-color: white;
  border-top: 1px solid #e2e8f0;
  display: flex;
  gap: 0.75rem;
  align-items: flex-end;
}

.input-wrapper {
  position: relative;
  width: 100%;
}

.function-buttons {
  position: absolute;
  right: 10px;
  bottom: 10px;
  display: flex;
  gap: 8px;
}

.function-button {
  border: 1px solid #e2e8f0;
  background-color: #fff;
  color: #64748b;
  transition: all 0.2s;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.function-button:hover:not([disabled]) {
  background-color: #f8fafc;
  color: #3b82f6;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.active-button {
  background-color: #eff6ff !important;
  color: #2563eb !important;
  border-color: #bfdbfe !important;
}

.send-button {
  padding: 0.75rem 1.5rem;
  font-weight: 500;
}

.login-notice {
  padding: 1rem 1.5rem;
  background-color: #f1f5f9;
}

/* 历史记录面板 */
.history-panel {
  width: 0;
  background-color: white;
  border-left: 1px solid #e2e8f0;
  transition: width 0.3s ease;
  overflow: hidden;
}

.history-panel-open {
  width: 320px;
}

.history-panel-header {
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e2e8f0;
}

.history-panel-header h3 {
  margin: 0;
  font-size: 1rem;
  color: #1e293b;
}

.history-list {
  padding: 1rem;
  height: calc(100% - 53px);
  overflow-y: auto;
}

.history-items {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.history-item {
  padding: 0.75rem;
  border-radius: 0.5rem;
  background-color: #f8fafc;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e2e8f0;
}

.history-item:hover {
  background-color: #f1f5f9;
  border-color: #cbd5e1;
}

.history-question {
  font-weight: 500;
  color: #334155;
  margin-bottom: 0.25rem;
}

.history-time {
  font-size: 0.75rem;
  color: #64748b;
}

.no-history, .history-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #64748b;
  font-size: 0.875rem;
}

@media (max-width: 768px) {
  .ai-chat-container {
    grid-template-columns: 1fr;
  }
  
  .history-panel {
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
    z-index: 10;
    box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
  }
    .chat-header {
    padding: 1rem;
    width: 100%; /* 在小屏幕上恢复为全宽 */
  }
  
  .chat-title {
    font-size: 1.25rem;
  }
  
  .chat-history {
    padding: 1rem;
  }
  
  .welcome-message {
    padding: 1.5rem;
  }
  
  .suggestion-list {
    flex-direction: column;
    align-items: stretch;
  }
  
  .chat-input-container {
    padding: 0.75rem;
  }
  
  .message-content {
    max-width: calc(100% - 45px);
  }
}
</style>
